//
//  Reg3ViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 15/12/6.
//  Copyright © 2015年 sgone. All rights reserved.
//

#import "Reg3ViewController.h"
//上传图片到七牛
#import "QiniuSDK.h"
#import "MBProgressHUD+MJ.h"
#import "AFNetworking.h"
#import "CustomViewController.h"
#import "LoginViewController.h"

@interface Reg3ViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong) UIImageView *imageview1;
@property(nonatomic,strong) UIImageView *imageview2;
//网路请求
@property(nonatomic,strong)AFHTTPSessionManager *manager;


////上传七牛服务器
@property (nonatomic, strong) QNUploadManager *uploader;
//获得七牛的token的数据
@property(nonatomic,strong) NSString *QNtoken;

//上传到七牛服务器所进行的拼接字符串
@property (nonatomic, copy) NSString *nameKey1;
////上传到七牛服务器所进行的拼接字符串
@property (nonatomic, copy) NSString *nameKey2;

//上传到七牛形成的网络路径
@property (copy, nonatomic)NSString *filePath;



//图像选择器
@property(nonatomic,strong) UIImagePickerController *picker1;
@property(nonatomic,strong) UIImagePickerController*picker2;



@end

@implementation Reg3ViewController


{
    //imagePickerView进行处理
    
    UIImagePickerController *_ctrl1;
    UIImagePickerController *_ctrl2;
    
}



//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}





- (void)viewDidLoad {
    
    [super viewDidLoad];

    self.titleLabel.text = @"注  册";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    self.backBtn.hidden = NO;
    self.tableView.scrollEnabled = NO;
    
    self.view.backgroundColor = BACKGROUND1;
    
    
    //获得囚牛token;
    
    
    //获取七牛token
    [self getQiniuToken];
    
}



-(void)back:(id)sender
{

    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma  mark获取七牛的token


//通过七牛上传图片
- (void)getQiniuToken
{
    
    //    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    //    [MBProgressHUD showMessage:@"加载中"];
    NSString *str = [NSString stringWithFormat:@"http://app.sgone.cn/appapi_v4/wholesaler_common/get_private_storage_token"];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil)
        {
            return ;
        }
        //解析服务器返回来的json数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        
        NSString *token = [[dict objectForKey:@"data"] objectForKey:@"upToken"];
        NSNumber *expire = [[dict objectForKey:@"data"] objectForKey:@"expire"];
        
        
        self.QNtoken = token;
        
        //        NSLog(@"输出的responsedata是  %@",dict) ;
        
        if (token != nil)
        {
//            NSLog(@"-----------------%@商品头像获取七牛token成功：%@     %@",token,expire,dict);
            
            
            
            
        }
        
    }];
    
    
}





-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;


}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 2;


}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 120;


}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];

    view1.backgroundColor = BACKGROUND1;
    [self.view addSubview:view1];
    
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 40,ViewWidth-20 , 38)];
    imageview.image = [UIImage imageNamed:@"register_3"];
    [view1 addSubview:imageview];
    
    
    
    
    return view1;




}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{


    return 120;


}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

{

    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
    view2.backgroundColor = BACKGROUND1;
    [self.view addSubview:view2];
    
    
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 30, ViewWidth-40, 44)];
    
    [btn.layer setMasksToBounds:YES];
    [btn.layer setCornerRadius:3.0];

    [btn setTitle:@"提 交" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [btn setTitleColor:BenSe_COLOR forState:UIControlStateNormal];
    btn.backgroundColor  =[UIColor whiteColor];
    [view2 addSubview:btn];
    [btn addTarget:self action:@selector(tijao:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    return view2;






}


#pragma mark 提交到服务器.将所有注册信息进行上传到服务器上，跳转到主页面
-(void)tijao:(id)sender
{
//判断是否传照片
    if (self.nameKey1.length == 0 || self.nameKey2.length == 0) {
        
        [self.view makeToast:@"请上传照片"];
        return;
        
    }
    
//    
//    
//    NSLog(@"%@  %@  %@  %@  %@  %@  %@  %@  %@  %@  %@  %@  %@   %@ %@  %@  %@ %@",self.dataHandler.phone,self.dataHandler.code,self.dataHandler.name,self.dataHandler.password, self.dataHandler.latitude ,self.dataHandler.longtitude,self.dataHandler.shen,self.dataHandler.shi,self.dataHandler.qu ,self.dataHandler.dizhi,self.dataHandler.shichang,self.dataHandler.fanwei, self.dataHandler.jiage, self.dataHandler.dianshu,self.dataHandler.yunfei,self.dataHandler.zjyunfei,self.nameKey1,self.nameKey2);
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *urlStr = [NSString stringWithFormat:@"%@register",SERVER_ADDRESS];
    NSDictionary *params = @{@"wTel" : self.dataHandler.phone ,@"last_code" : self.dataHandler.code ,@"wholesaler_name" : self.dataHandler.name ,@"passwd" : self.dataHandler.password , @"addX" : self.dataHandler.latitude ,@"addY" : self.dataHandler.longtitude ,@"province" : self.dataHandler.shen , @"city" : self.dataHandler.shi ,@"town" : self.dataHandler.qu ,@"address" : self.dataHandler.dizhi,@"market" : self.dataHandler.shichang, @"push_radius" : self.dataHandler.fanwei ,@"start_price" : self.dataHandler.jiage ,@"device_type" : @"1", @"near_range" :self.dataHandler.juli , @"far_range" : @"", @"start_point" : self.dataHandler.dianshu ,@"near_price" : self.dataHandler.yunfei ,@"over_price" : self.dataHandler.zjyunfei, @"image1" : self.nameKey1 , @"image2" : self.nameKey2};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0 ) {
            
            
//            NSLog(@"上传成功");
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
//            //上传服务器成功进入首页
//            CustomViewController *cus = [[CustomViewController alloc]initWithNibName:nil bundle:nil];
//            
//            
//            //将所需的数据进行保存
//            self.dataHandler.phone = self.dataHandler.phone;
//            [self.dataHandler saveLocalData:@"" value:<#(id)#>]
            
            
            
            
            
            
            

            
            
            //进入登录页面重新登录
            
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            LoginViewController *login=[[LoginViewController alloc]init];
            [self presentViewController:login animated:YES completion:nil];

            
            
            
            
        }
        else
        {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"result_msg"]];
            UIAlertView *alter =[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];

        
        
        
        }
        
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        UIAlertView *alater = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络" delegate:nil cancelButtonTitle:nil  otherButtonTitles:@"确定", nil];
        [alater show];
        
    }];




}










-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 70;


}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor grayColor];
        
        
    }
    
    if (indexPath.row == 0) {
        
        cell.textLabel.text = @"营业执照/身份证正面";
               cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        self.imageview1 = [[UIImageView alloc]initWithFrame:CGRectMake(ViewWidth-110, 0, 80, 70)];
        [cell addSubview:self.imageview1];
//        self.imageview1.backgroundColor = [UIColor greenColor];
        self.imageview1.image = [UIImage imageNamed:@"nopic1"];
        //添加button
        UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(ViewWidth-140, 0, 140, 70)];
        [cell addSubview:btn1];
        
        [btn1 addTarget:self action:@selector(btn1:) forControlEvents:UIControlEventTouchUpInside ];
        
        
        
    }
    else if (indexPath.row == 1)
    {
    
    cell.textLabel.text = @"组织机构代码/身份证反面";
               cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        self.imageview2 = [[UIImageView alloc]initWithFrame:CGRectMake(ViewWidth-110, 0, 80, 70)];
        [cell addSubview:self.imageview2];
//        self.imageview2.backgroundColor = [UIColor redColor];
        self.imageview2.image = [UIImage imageNamed:@"nopic1"];

        
        //添加button
        UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(ViewWidth-140, 0, 140, 70)];
        [cell addSubview:btn2];
        
        [btn2 addTarget:self action:@selector(btn2:) forControlEvents:UIControlEventTouchUpInside ];
    
    }
    
    
    return cell;


}



#pragma mark 进行按钮操作
-(void)btn1:(id)sedner
{


    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    
    [actionSheet showInView:self.view];
    actionSheet.tag = 110;

}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    if (actionSheet.tag == 110) {
        
    
    
    if (buttonIndex == 2) {
        
        return;
    }
    
        
        
    if(buttonIndex==1)
    {
        
        //调用系统相册
        _ctrl1=[[UIImagePickerController alloc]init];
        _ctrl1.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        _ctrl1.delegate=self;
        _ctrl1.allowsEditing = YES;
        [self addChildViewController:_ctrl1];
        self.tabBarController.tabBar.alpha = 0;
        [self.view addSubview:_ctrl1.view];
        self.tabBarController.tabBar.hidden = YES;
        
        
        
        
    }
    else if (buttonIndex==0)
        
    {
        
        
        _ctrl1=[[UIImagePickerController alloc]init];
        _ctrl1.sourceType=UIImagePickerControllerSourceTypeCamera;
        _ctrl1.delegate=self;
        _ctrl1.allowsEditing = YES;
        
        [self addChildViewController:_ctrl1];
        
        [self.view addSubview:_ctrl1.view];
        
        
        
        
    }

        
        
        
        
        
    }
    
    
    else if (actionSheet.tag == 120)
    
    {
    
    
    
        if (buttonIndex == 2) {
            
            return;
        }
        
        
        
        if(buttonIndex==1)
        {
            
            //调用系统相册
            _ctrl2=[[UIImagePickerController alloc]init];
            _ctrl2.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            _ctrl2.delegate=self;
            _ctrl2.allowsEditing = YES;
            [self addChildViewController:_ctrl2];
            self.tabBarController.tabBar.alpha = 0;
            [self.view addSubview:_ctrl2.view];
            self.tabBarController.tabBar.hidden = YES;
            
            
            
            
        }
        else if (buttonIndex==0)
            
        {
            
            
            _ctrl2=[[UIImagePickerController alloc]init];
            _ctrl2.sourceType=UIImagePickerControllerSourceTypeCamera;
            _ctrl2.delegate=self;
            _ctrl2.allowsEditing = YES;
            
            [self addChildViewController:_ctrl2];
            
            [self.view addSubview:_ctrl2.view];
            
            
            
            
        }
        
        
    
    
    }
}



#pragma mark - ImagePickerController Delegate
//点击取消按钮时候调用
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
    if (_ctrl1)
    {
        [_ctrl1.view removeFromSuperview];
        self.navigationController.navigationBar.hidden=YES;
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
        
    }
    else if (_ctrl2)
    {
    
        [_ctrl2.view removeFromSuperview];
        self.navigationController.navigationBar.hidden=YES;
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];

    
    
    }
}

//点击确定按钮
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    
    if (picker == _ctrl1) {
    
    UIImage *image=[info objectForKey:UIImagePickerControllerEditedImage];
    
    
    self.imageview1.image=image;
    
    
    
    self.filePath = [self.dataHandler dataFilePath:@"pifazz.jpg"];
    
    NSData *webData = UIImageJPEGRepresentation(self.imageview1.image, 0.5);
    [webData writeToFile:self.filePath atomically:YES];
    [self uploadImage1];
    [picker.view removeFromSuperview];
    self.navigationController.navigationBar.hidden= YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    }
    
    else if (picker == _ctrl2)
    {
    
    
        UIImage *image=[info objectForKey:UIImagePickerControllerEditedImage];
        
        
        self.imageview2.image=image;
        
        
        
        self.filePath = [self.dataHandler dataFilePath:@"pifazzdm.jpg"];
        
        NSData *webData = UIImageJPEGRepresentation(self.imageview2.image, 0.5);
        [webData writeToFile:self.filePath atomically:YES];
        [self uploadImage2];
        [picker.view removeFromSuperview];
        self.navigationController.navigationBar.hidden= YES;
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];

    
    
    }
    
    
}






//网络上传到七牛的操作步骤以及属性
#pragma mark - upload qiniu
- (void)uploadImage1{
    
    //获得的商品图片，需要传递给服务器
    self.nameKey1 = [NSString stringWithFormat:@"pfzz-%@-%@.jpg",self.dataHandler.phone, [self.dataHandler timeString]];
    
    //    NSLog(@"图片  %@    %@  %@",self.nameKey,self.dataHandler.phone,self.dataHandler.uToken);
    
    if (!self.uploader)
    {
        
        self.uploader = [[QNUploadManager alloc]init];
        
    }
    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [self.uploader putFile:_filePath key:self.nameKey1 token:self.QNtoken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        
        [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
//        NSLog(@"%@", info);
//        NSLog(@"七牛返回信息%@", resp);
    } option:nil];
    
    
    
    
}




//网络上传到七牛的操作步骤以及属性
#pragma mark - upload qiniu
- (void)uploadImage2{
    
    //获得的商品图片，需要传递给服务器
    self.nameKey2 = [NSString stringWithFormat:@"pfzzzp-%@-%@.jpg",self.dataHandler.phone, [self.dataHandler timeString]];
    
    //    NSLog(@"图片  %@    %@  %@",self.nameKey,self.dataHandler.phone,self.dataHandler.uToken);
    
    if (!self.uploader)
    {
        
        self.uploader = [[QNUploadManager alloc]init];
        
    }
    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    [self.uploader putFile:_filePath key:self.nameKey2 token:self.QNtoken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        
        [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
//        NSLog(@"%@", info);
//        NSLog(@"七牛返回信息%@", resp);
    } option:nil];
    
    
    
    
}


-(void)btn2:(id)sender
{

    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    
    [actionSheet showInView:self.view];
    actionSheet.tag = 120;
    





}

@end
